package com.framework.core.mvp;

import com.framework.core.utils.ExceptionUtil;
import com.framework.core.bean.RestError;

import rx.Subscriber;

/**
 * @author shenmengchao
 * @version 1.0.0
 * @date 2017/7/18
 * @description
 */

public abstract class IObserver<T> extends Subscriber<T>{

    private BasePresenter mBasePresenter;
    private boolean mIsShowLoadingDialog;

    public IObserver(BasePresenter basePresenter){
        this.mBasePresenter = basePresenter;
    }

    public IObserver(BasePresenter basePresenter, boolean isShowLoadingDialog){
        this.mBasePresenter = basePresenter;
        this.mIsShowLoadingDialog = isShowLoadingDialog;
    }

    public abstract boolean onFailed(RestError restError);

    @Override
    public void onStart() {
        super.onStart();
        if (!isViewAttached()) return;
        if (mIsShowLoadingDialog) {
            this.mBasePresenter.getMvpView().onShowLoadingDialog();
        }
    }

    @Override
    public void onCompleted() {
        if (!isViewAttached()) return;
        if (mIsShowLoadingDialog) {
            this.mBasePresenter.getMvpView().onDismissLoadingDialog();
        }
    }

    @Override
    public void onError(Throwable e) {
        if (!isViewAttached()) return;
        BaseView mvpView = this.mBasePresenter.getMvpView();
        mvpView.onDismissLoadingDialog();
        mvpView.onSetRefreshComplete();
        RestError restError = ExceptionUtil.generateRestError(e);
        onFailed(restError);
    }

    private boolean isViewAttached() {
        return mBasePresenter == null ? false : mBasePresenter.isViewAttached();
    }
}
